package net.liteheaven.xblib.common.rom;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

public class ShellUtil {

    private static final String TAG = "ShellUtil";
    
    public static class CmdProcess{
    	
    	private String cmd;
    	private Process process;
    	private InputStream istream;
    	private OutputStream ostream;
    	private InputStream estream;
    	
    	public CmdProcess(String cmd){
    		this.cmd = cmd;
    	}
    	
    	public Process getProcess(){
    		return process;
    	}
    	
    	public void exec(){
    		Runtime runtime = Runtime.getRuntime();
    		try {
				process = runtime.exec(cmd);
				if (process != null){
					istream = process.getInputStream();
					ostream = process.getOutputStream();
					estream = process.getErrorStream();
				}
			} catch (IOException e) {
				e.printStackTrace();
				process = null;
			}
    	}
    	
    	public InputStream is(){
    		return istream;
    	}
    	
    	public OutputStream os(){
    		return ostream;
    	}
    	
    	public InputStream es(){
    		return estream;
    	}
    }

    public static StringBuffer execCommand(String command){

        StringBuffer sb = new StringBuffer("");

        Runtime runtime = Runtime.getRuntime();

        Process process;
        try {
            process = runtime.exec(command);
        } catch (IOException e) {
            e.printStackTrace();
            process = null;
        }

        if (process == null) {
            return sb;
        }

        InputStream inputstream = process.getInputStream();
        InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
        BufferedReader bufferedreader = new BufferedReader(inputstreamreader);

        try {
            String line;
            while ((line = bufferedreader.readLine()) != null) {
                sb.append(line);
                sb.append('\n');
            }
        } catch (IOException e) {
            e.printStackTrace();
            sb.delete(0,sb.length()-1);
            android.util.Log.e(TAG, e.getMessage());
            return sb;
        }

        try {
            if (process.waitFor() != 0) {
                android.util.Log.e(TAG, "exit value = " + process.exitValue());
            }
        }
        catch (InterruptedException e) {
            android.util.Log.e(TAG, e.getMessage());
        }

        return sb;
    }
    
    public static int getUid(int pid){

        final String cmd1 = "cat /proc/"+pid+"/cgroup";
        final String cmd2 = "grep cpuacct";
        int uid;
        
        final String [] cmds = {cmd1, cmd2};
        String lines = execCmds(cmds);
        try {    
        	String [] parts = lines.split("/uid/");
            String strUid = parts[1];
            uid = Integer.valueOf(strUid);
		} catch (Exception e) {
			android.util.Log.e(TAG, e.getMessage());
            uid = 0;
		}
        return uid;
    }
    
    public static String execAfter(String cmd1, String cmd2){
    	final String [] cmds = {cmd1, cmd2};
    	return execCmds(cmds);
    }
    
    public static String execCmds(String [] cmd){
    	String result = "";
    	
    	if (cmd == null){
    		return result;
    	}
    	
    	InputStream lastIs = null;
    	
    	for (int i = 0; i < cmd.length; i++) {
			CmdProcess process = new CmdProcess(cmd[i]);
			process.exec();
			InputStream is = process.is();
			OutputStream os = process.os();
			InputStream es = process.es();
			
			if (lastIs != null){
				os2Is(os, lastIs);
			}
			
			if (i == cmd.length - 1){
				if (is != null){
					result = readStrFromIs(is);	
				}else{
					if (es != null){
						result = readStrFromIs(es);
					}
				}
				break;
			}			
			
			lastIs = is;
		}
    	
    	return result;
    }
    
    private static void os2Is(OutputStream os, InputStream is){
    	try {
            byte[] b = new byte[512];
            int read = 1;
            while (read > -1) {
                read = is.read(b, 0, b.length);
                if (read > -1) {
                	os.write(b, 0, read);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("Broken pipe", e);
        } finally {
            try {
                is.close();
            } catch (Exception e) {
            }
            try {
                os.close();
            } catch (Exception e) {
            }
        }
    }
    
    private static String readStrFromIs(InputStream is){
    	StringBuffer sb = new StringBuffer("");
		InputStreamReader inputstreamreader = new InputStreamReader(is);
        BufferedReader bufferedreader = new BufferedReader(inputstreamreader);

        try {
            String line;
            while ((line = bufferedreader.readLine()) != null) {
                sb.append(line);
                sb.append('\n');
            }
        } catch (IOException e) {
            sb.delete(0,sb.length()-1);
        }
        
        String result = (sb == null) ? "" : sb.toString();
        return result;
    }
}
